package soul.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by sunzhengjie on 2017/2/13.
 */
public class UploadUtil {

    public static final String FILE_PATH = "C:\\Users\\dell\\Desktop\\";
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadUtil.class);

    public static String upload(List<String> base64files) {
        List<String> imagesPath = new ArrayList<>();
        try {
            for (String base64file : base64files) {
                LOGGER.debug("上传文件的数据：" + base64file);
                String dataPrix = "";
                String data = "";

                LOGGER.debug("对数据进行判断");
                if (base64file == null || "".equals(base64file)) {
                    throw new RuntimeException("上传失败，上传图片数据为空");
                } else {
                    String[] d = base64file.split("base64,");
                    if (d.length == 2) {
                        dataPrix = d[0];
                        data = d[1];
                    } else {
                        throw new RuntimeException("上传失败，数据不合法");
                    }
                }

                LOGGER.debug("对数据进行解析，获取文件名和流数据");
                String suffix = "";
                if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//编码的jpeg图片数据
                    suffix = ".jpg";
                } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//编码的icon图片数据
                    suffix = ".ico";
                } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//编码的gif图片数据
                    suffix = ".gif";
                } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//编码的png图片数据
                    suffix = ".png";
                } else {
                    throw new RuntimeException("上传图片格式不合法");
                }

                //因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
                byte[] bs = Base64Utils.decodeFromString(data);
                File file = new File(FILE_PATH + UUID.randomUUID() + suffix);
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new RuntimeException("生成文件失败");
                }

                FileOutputStream out = new FileOutputStream(file);
                out.write(bs);
                out.close();
                imagesPath.add(file.getAbsolutePath());
            }
            String pathes = "";
            for (String s : imagesPath) {
                pathes += s + ",";
            }
            LOGGER.debug("上传成功");
            return pathes;
        } catch (Exception ex) {
            throw new RuntimeException("上传文件失败");
        }
    }
}
